package com.example.locationtest;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.BitmapFactory;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.locationtest.lib.KalmanLocationManager;
import com.mapbox.geojson.Point;
import com.mapbox.geojson.Polygon;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.geometry.LatLngBounds;
import com.mapbox.mapboxsdk.geometry.LatLngQuad;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.PropertyFactory;
import com.mapbox.mapboxsdk.style.layers.RasterLayer;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;

import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.mapboxsdk.style.sources.ImageSource;


import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {
    /**
     * 位置GPS更新时间
     */
    private static final long GPS_TIME = 1000;
    /**
     * 位置网络定位更新时间
     */
    private static final long NET_TIME = 1000;
    /**
     * 过滤器触发时间
     */
    private static final long FILTER_TIME = 1000;
    private String path;

    private KalmanLocationManager mKalmanLocationManager;
    private MapView mapView;
    private MapboxMap map;
    private GeoJsonSource sourceGPS;
    private GeoJsonSource indoor;
    private ImageSource imageSource;
    //    private GeoJsonSource sourceNet;
    private GeoJsonSource sourceKalMan;
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");
    public static final int RESULT_CODE = 1001;
    public final double[] BOUNDS = new double[]{35.267949, 115.465582, 35.268049, 115.465670};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "pk.eyJ1IjoiemhvdTM0MzQiLCJhIjoiY2wyNjR4ajFlMjFpazNicW9iczN6cGVzaCJ9.oxnj2y9lbyEg3s-k3SEFsQ");
        setContentView(R.layout.activity_main);

        mapView = findViewById(R.id.mapView);

        //生成文件夹之后，再生成文件，不然会出错

        mapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(@NonNull MapboxMap mapboxMap) {
                map = mapboxMap;
                sourceGPS = new GeoJsonSource("gps");
                sourceKalMan = new GeoJsonSource("kalman");
                indoor = new GeoJsonSource("indoor");
                imageSource = new ImageSource("test", new LatLngQuad(
                        new LatLng(BOUNDS[2], BOUNDS[1]),
                        new LatLng(BOUNDS[2], BOUNDS[3]),
                        new LatLng(BOUNDS[0], BOUNDS[3]),
                        new LatLng(BOUNDS[0], BOUNDS[1])
                ),
                        R.drawable.indoor);


                mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {

                    @Override
                    public void onStyleLoaded(@NonNull Style style) {
                        style.addLayer(new RasterLayer("indoor", "test"));

                        //设置定位结果样式
                        style.addImage(("marker_gps"), BitmapFactory.decodeResource(
                                getResources(), R.mipmap.gps));
                        style.addImage(("marker_kalman"), BitmapFactory.decodeResource(
                                getResources(), R.mipmap.kalman));
                        style.addImage(("indoor"), BitmapFactory.decodeResource(
                                getResources(), R.drawable.indoor));
                        style.addSource(sourceGPS);
                        style.addSource(sourceKalMan);
                        style.addSource(indoor);
                        style.addSource(imageSource);

                        style.addLayer(new SymbolLayer("gps", "gps")
                                .withProperties(
                                        PropertyFactory.iconImage("marker_gps"),
                                        PropertyFactory.iconIgnorePlacement(true),
                                        PropertyFactory.iconAllowOverlap(true)
                                ));
                        style.addLayer(new SymbolLayer("kalman", "kalman")
                                .withProperties(
                                        PropertyFactory.iconImage("marker_kalman"),
                                        PropertyFactory.iconIgnorePlacement(true),
                                        PropertyFactory.iconAllowOverlap(true)
                                ));



                        locateImg(null);
                        //动态请求权限
//                        methodRequiresTwoPermission();
                    }
                });
            }
        });
    }

    //动态权限框架
    @AfterPermissionGranted(RESULT_CODE)
    private void methodRequiresTwoPermission() {
        String[] perms = {Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(MainActivity.this, perms)) {
            // 已有权限
            mKalmanLocationManager = new KalmanLocationManager(MainActivity.this);
            mKalmanLocationManager.requestLocationUpdates(
                    KalmanLocationManager.UseProvider.GPS_AND_NET, FILTER_TIME, GPS_TIME, NET_TIME, mLocationListener, true);

        } else {

            EasyPermissions.requestPermissions(MainActivity.this, "请求获取您的位置信息和本地读写权限",
                    RESULT_CODE, perms);
        }
    }

    public void locatePosition(View view) {
        methodRequiresTwoPermission();
    }
    public void locateImg(View view) {
        if (map != null) {
            LatLngBounds latLngBounds = LatLngBounds.from(BOUNDS[2], BOUNDS[3], BOUNDS[0], BOUNDS[1]);
            CameraPosition position = map.getCameraForLatLngBounds(latLngBounds);
            map.setCameraPosition(position);
            map.setLatLngBoundsForCameraTarget(latLngBounds);
            map.setMinZoomPreference(21.3);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mapView != null) {
            mapView.onStart();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();

    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);

    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onStop();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mKalmanLocationManager != null) {
            mKalmanLocationManager.requestLocationUpdates(
                    KalmanLocationManager.UseProvider.GPS_AND_NET, FILTER_TIME, GPS_TIME, NET_TIME, mLocationListener, true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mKalmanLocationManager != null) {
            mKalmanLocationManager.removeUpdates(mLocationListener);
        }
    }

    private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
            CameraPosition position = new CameraPosition.Builder()
                    .target(latLng)
                    .zoom(16)
                    .tilt(20)
                    .build();
            if (map != null) {
                map.animateCamera(CameraUpdateFactory.newCameraPosition(position));
            }
            if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
                Log.e("定位", "GPS定位");
                sourceGPS.setGeoJson(Point.fromLngLat(location.getLongitude(), location.getLatitude()));

            }

            if (location.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
                Log.e("定位", "网络定位");
//                sourceNet.setGeoJson(Point.fromLngLat(location.getLongitude(),location.getLatitude()));

            }

            if (location.getProvider().equals(KalmanLocationManager.KALMAN_PROVIDER)
            ) {
                Log.e("定位", "卡尔曼滤波结果");
                sourceKalMan.setGeoJson(Point.fromLngLat(location.getLongitude(), location.getLatitude()));
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

            String statusString = "Unknown";

            switch (status) {

                case LocationProvider.OUT_OF_SERVICE:
                    statusString = "Out of service";
                    break;

                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    statusString = "Temporary unavailable";
                    break;

                case LocationProvider.AVAILABLE:
                    statusString = "Available";
                    break;
            }

            Toast.makeText(
                    MainActivity.this,
                    String.format("Provider '%s' status: %s", provider, statusString),
                    Toast.LENGTH_SHORT)
                    .show();
        }

        @Override
        public void onProviderEnabled(String provider) {

            Toast.makeText(
                    MainActivity.this, String.format("Provider '%s' enabled", provider), Toast.LENGTH_SHORT).show();

            // Remove strike-thru in label
            if (provider.equals(LocationManager.GPS_PROVIDER)) {


            }

            if (provider.equals(LocationManager.NETWORK_PROVIDER)) {


            }
        }

        @Override
        public void onProviderDisabled(String provider) {

            Toast.makeText(
                    MainActivity.this, String.format("Provider '%s' disabled", provider), Toast.LENGTH_SHORT).show();

            // Set strike-thru in label and hide accuracy circle
            if (provider.equals(LocationManager.GPS_PROVIDER)) {


            }

            if (provider.equals(LocationManager.NETWORK_PROVIDER)) {


            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

}